package com.liwei.lwmail.elasticsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.liwei.common.to.es.SkuEsModel;
import com.liwei.lwmail.elasticsearch.config.ElasticSearchConfig;
import com.liwei.lwmail.elasticsearch.constant.EsConstant;
import com.liwei.lwmail.elasticsearch.service.ElasticProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service("elasticProductSaveService")
public class ElasticProductSaveServiceImpl implements ElasticProductSaveService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public Boolean productUpStatus(List<SkuEsModel> skuEsModels) throws IOException {

        //1、建立索引 product，建立好映射关系

        //2、给es保存数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            //构造索引请求
            IndexRequest request = new IndexRequest(EsConstant.PRODUCT_INDEX);
            request.id(skuEsModel.getSkuId().toString());
            String jsonString = JSON.toJSONString(skuEsModel);
            request.source(jsonString, XContentType.JSON);

            bulkRequest.add(request);
        }

        //批量操作
        BulkResponse bulkResponse = client.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);

        //TODO 如果批量有错误，可以根据响应结果处理
        boolean hasFailures = bulkResponse.hasFailures();
        List<String> collect = Arrays.stream(bulkResponse.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("商品成功,{}",collect);

        return  !hasFailures;
    }
}
